package phoeics.authoryserver.webservice.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class TokenAuthenticationService {
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TokenAuthenticationService.class);
	static final long EXPIRATIONTIME = 432_000_000;     // 5天
    static final String SECRET = "P@ssw02d";            // JWT密码
    static final String TOKEN_PREFIX = "Bearer";        // Token前缀
    static final String HEADER_STRING = "Authorization";// 存放Token的Header Key
    public static void addAuthentication(HttpServletResponse response, String username) {
    	 String jwtStr = Jwts.builder().claim("authorities", "ROLE_ADMIN,AUTH_WRITE")
    			 .setSubject(username).setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
    			 .signWith(SignatureAlgorithm.HS512, SECRET).compact();
    	 try {
             response.setContentType("application/json");
             response.setStatus(HttpServletResponse.SC_OK);
             response.getOutputStream().println(jwtStr);
         } catch (IOException e) {
             e.printStackTrace();
         }
    }
    public  static Authentication getAuthentication(HttpServletRequest request) {
    	String token = request.getHeader(HEADER_STRING);
    	if (token != null) {
    		Claims claims = Jwts.parser().setSigningKey(SECRET)
    				.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
    				.getBody();
    		String user = claims.getSubject();
    		 List<GrantedAuthority> authorities =  AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));
    		 return user != null ?
                     new UsernamePasswordAuthenticationToken(user, null, authorities) :
                     null;
    	}
    	return null;
    }
}
